﻿namespace groopServer.Common.Persistence.Repositories {
    using System;
    using System.Collections.Generic;
    using groopServer.Model.Domain;
    using NHibernate;
    using NHibernate.Expression;

    public class RepositoryBase<TEntity> : ICRUDRepository<TEntity>
        where TEntity : EntityBase, new() {
        protected readonly ISessionBuilder _sessionBuilder;

        public RepositoryBase(ISessionBuilder sessionFactory) {
            _sessionBuilder = sessionFactory;
        }

        #region ICRUDRepository<TEntity> Members

        public void Create(TEntity entity) {
            using (ISession session = GetSession()) {
                session.Save(entity);
                session.Flush();
            }
        }

        public TEntity Retrieve(Guid entityId) {
            TEntity entity;

            using (ISession session = GetSession()) {
                ICriteria criteria = session.CreateCriteria(typeof (TEntity));
                criteria.Add(Expression.Eq("Id", entityId));

                entity = criteria.UniqueResult<TEntity>();
            }

            return entity;
        }

        public IList<TEntity> RetrieveAll() {
            IList<TEntity> itemList;

            using (ISession session = GetSession()) {
                ICriteria targetObjects = session.CreateCriteria(typeof (TEntity));
                itemList = targetObjects.List<TEntity>();
            }

            return itemList;
        }

        public void Update(TEntity entity) {
            using (ISession session = GetSession()) {
                session.Update(entity);
                session.Flush();
            }
        }

        public void Delete(TEntity entity) {
            using (ISession session = GetSession()) {
                session.Delete(entity);
                session.Flush();
            }
        }

        #endregion

        protected ISession GetSession() {
            ISession session = _sessionBuilder.GetSession();
            return session;
        }
        }
}